package com.zhengb.nettydemos.chapter5.delimiter;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhengbo on 2019/4/8.
 */
//@Slf4j
public class EchoClientHandler extends ChannelHandlerAdapter {

    private final static AtomicInteger counter = new AtomicInteger(0);

    private final static Logger logger = LoggerFactory.getLogger(EchoClientHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String echoRequest = "Hi,Welcome to netty" + Constants.DELIMITER_STR;

        for (int i = 0; i < 10; i++) {
            ByteBuf request = Unpooled.copiedBuffer(echoRequest.getBytes());
            ctx.writeAndFlush(request);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("echo client receive from server,message:{},counter is:{}",
                msg, counter.incrementAndGet());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Echo client error:{}", cause.getMessage());
        ctx.close();
    }
}
